package com.cxh.supermarket.common.filter;

import cn.hutool.core.util.ObjectUtil;
import com.cxh.supermarket.common.core.domain.R;
import com.cxh.supermarket.common.utils.JsonUtils;
import java.io.IOException;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

/**
 * 功能描述:
 *
 * @author zxl
 * @since 2024/9/25
 */
public class EmojiFilter implements Filter {
  @Override
  public void init(FilterConfig filterConfig) throws ServletException {
    Filter.super.init(filterConfig);
  }

  @Override
  public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
      throws IOException, ServletException {
    // 如果是 multipart/form-data 类型的请求，直接跳过处理
    if (servletRequest.getContentType() != null && servletRequest.getContentType().startsWith("multipart/form-data")) {
      filterChain.doFilter(servletRequest, servletResponse);
      return;
    }
    // 处理请求
    String body = servletRequest.getReader().lines()
        .collect(Collectors.joining(System.lineSeparator()));
    // 替换emoji表情
    if (ObjectUtil.isNotNull(body)) {
      String regex = "[\\x{1F300}-\\x{1F5FF}\\x{1F600}-\\x{1F64F}\\x{1F680}-\\x{1F6FF}\\x{2600}-\\x{26FF}\\x{2700}-\\x{27BF}]+";
      Pattern pa = Pattern.compile(regex);
      if (pa.matcher(body).find()) {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json");
        String failStr = JsonUtils.toJsonString(R.fail("非法字符"));
        response.getWriter().write(failStr);
        return; // 结束请求处理
      }
    }
    // 继续过滤链
    filterChain.doFilter(servletRequest, servletResponse);
  }


  @Override
  public void destroy() {
    Filter.super.destroy();
  }
}
